package cn.anecansaitin.not_enough_harness.client;

import cn.anecansaitin.not_enough_harness.NotEnoughHarness;
import cn.anecansaitin.not_enough_harness.common.ModCapabilities;
import cn.anecansaitin.not_enough_harness.common.capability.harness_capability.HarnessCapabilityHandler;
import cn.anecansaitin.not_enough_harness.common.payload.UsingHarnessCapability;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.animal.HappyGhast;
import net.minecraft.world.item.ItemStack;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.client.event.ClientTickEvent;
import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent;
import net.neoforged.neoforge.client.network.ClientPacketDistributor;
import net.neoforged.neoforge.common.util.Lazy;
import org.lwjgl.glfw.GLFW;

@EventBusSubscriber(value = Dist.CLIENT, modid = NotEnoughHarness.MOD_ID)
public class ModKeymappings {
    public static final Lazy<KeyMapping> HAPPY_GHAST_MOVE_DOWN = Lazy.of(() ->
            new KeyMapping(
                    "key." + NotEnoughHarness.MOD_ID + ".happy_ghast_move_down",
                    InputConstants.Type.KEYSYM,
                    GLFW.GLFW_KEY_LEFT_CONTROL,
                    KeyMapping.CATEGORY_MOVEMENT
                    )
    );
    public static final Lazy<KeyMapping> HARNESS_CAPABILITY = Lazy.of(() ->
            new KeyMapping(
                    "key." + NotEnoughHarness.MOD_ID + ".harness_capability",
                    InputConstants.Type.KEYSYM,
                    GLFW.GLFW_KEY_C,
                    KeyMapping.CATEGORY_MOVEMENT
            )
    );

    @SubscribeEvent
    public static void registerBindings(RegisterKeyMappingsEvent event) {
        event.register(HAPPY_GHAST_MOVE_DOWN.get());
        event.register(HARNESS_CAPABILITY.get());
    }

    @SubscribeEvent
    public static void keyListener(ClientTickEvent.Post event) {
        boolean capPress = false;

        while (HARNESS_CAPABILITY.get().consumeClick()) {
            capPress = true;
        }

        LocalPlayer player = Minecraft.getInstance().player;

        if (!capPress || !(player.getControlledVehicle() instanceof HappyGhast ghast)) {
            return;
        }

        ItemStack harness = ghast.getItemBySlot(EquipmentSlot.BODY);

        if (harness.isEmpty()) {
            return;
        }

        HarnessCapabilityHandler cap = harness.getCapability(ModCapabilities.HARNESS_CAPABILITY_HANDLER);

        if (cap == null) {
            return;
        }

        cap.use(harness, ghast, player);
        ClientPacketDistributor.sendToServer(UsingHarnessCapability.INSTANCE);
    }
}
